import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import bcrypt from 'bcryptjs';

async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success || !authResult.user || authResult.user.role !== 1) {
    throw new Error('权限不足');
  }

  const { id, password, ...updateData } = await req.json();

  if (!id) {
    throw new Error('ID 为必填项');
  }

  if (password) {
    updateData.password = await bcrypt.hash(password, 10);
  }

  const updatedUser = await prisma.user.update({
    where: { id },
    data: updateData,
  });

  const { password: _, ...safeUser } = updatedUser;

  return safeUser;
}

export const POST = withMiddleware(handler);